package com.wangzemin.leetcode.n019;

/**
 * Definition for singly-linked list.
 */

class ListNode {
    int val;
    ListNode next;

    ListNode() {
    }

    ListNode(int val) {
        this.val = val;
    }

    ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }
}

public class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        if (head == null) {
            return null;
        }
        ListNode fastNode = head;
        ListNode slowNode = head;
        ListNode slowBeforeNode = null;
        int fastCurrentLoc = 1;
        while (fastNode.next != null) {
            fastNode = fastNode.next;
            fastCurrentLoc++;
            if (fastCurrentLoc > n) {
                slowBeforeNode = slowNode;
                slowNode = slowNode.next;
            }
        }
        if (fastCurrentLoc < n) {
            return head;
        }
        if (slowBeforeNode==null){
            return slowNode.next;
        }
        slowBeforeNode.next = slowNode.next;
        return head;
    }
}
